package com.example.aggregation.shardingdemo.sharding;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Calendar;
import java.util.Collection;
import java.util.Date;

@Slf4j
public class OrderPreciseShardingAlgorithm implements PreciseShardingAlgorithm {
    @Override
    public String doSharding(Collection collection, PreciseShardingValue preciseShardingValue) {
        // collection中保存所有真实节点
        collection.stream().forEach((item)->{
            log.info("actual node table:{}",item);
        });
        final Date columnValue = (Date)preciseShardingValue.getValue();
        final String columnName = preciseShardingValue.getColumnName();
        final String logicTableName = preciseShardingValue.getLogicTableName();

        //preciseShardingValue中保存分片逻辑，包含逻辑表，分片字段和查询的条件值
        log.info("logic table name:{},rout column:{}", logicTableName, columnName);
        log.info("column value:{}", columnValue);

        //采用自定义的ID生成器后，ID的前四位数字就是年份
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(columnValue);
        final int year = calendar.get(Calendar.YEAR);

        //RedisOpsUtil redisOpsUtil = TulingmallOrderApplication.getBean("redisOpsUtil");
        //final Integer shardingKey = redisOpsUtil.get("shardingYear:" + year, Integer.class);

        if (year==2020) return "ds0";
        if (year==2021) return "ds1";
        //String actualNode = logicTableName+"_"+year;
        //返回的结构就是具体的实际表。sharddingsphere会把逻辑表改成这个实际表
        return null;
    }
}